package com.icinfo.cloud.provider.common.zzd;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.xxpt.gateway.shared.client.http.ExecutableClient;
import com.alibaba.xxpt.gateway.shared.client.http.PostClient;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request.BtnJsonList;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 浙证钉消息发送
 *
 * @author lxj
 * @data 2022/4/1
 */
@Slf4j
public class DingSendUtil {

    private static String miniappid = "2018082961119947";
    private static String nativebizid = "ding5d2dd335032d4436";
    private static String nativeagentid = "189989672";
    private static String worknotificationapi = "/message/workNotification";

    /**
     * 发送工作消息通知
     */
    public static boolean sendWorkNotification(DingMsg dingMsg) {
        ExecutableClient executableClient = getExecutableClient();
        PostClient postClient = executableClient.newPostClient(worknotificationapi);
        DingDingDto dingDingDto = dingMsg.getDingDingDto();

        JSONObject obj = new JSONObject();
        //卡片消息
        obj.put("title", dingDingDto.getTitle());
        obj.put("markdown", dingDingDto.getDingMsg());
        obj.put("btn_orientation", "1");
        if (CollectionUtils.isNotEmpty(dingDingDto.getBtnJsonListList())) {
            List<BtnJsonList> btnJsonList = dingDingDto.getBtnJsonListList();
            List<Object> btnJsonList2 = Lists.newArrayList();
            for (BtnJsonList jsonList : btnJsonList) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("title", jsonList.getTitle());
                //jsonObject.put("action_url", "dingtalk://dingtalkclient/action/open_micro_app?miniAppId=" + miniappid + "&agentId=" + nativeagentid + "&pVersion=1&packageType=1&corpId=" + nativebizid + "&page=" + jsonList.getActionUrl());
                jsonObject.put("action_pc_url", jsonList.getActionUrl());
                jsonObject.put("action_mobile_url", jsonList.getActionUrl());
                btnJsonList2.add(jsonObject);
            }
            obj.put("btn_json_list", btnJsonList2);
        }

        String msgType = "action_card";
        JSONObject msgObj = new JSONObject();
        msgObj.put("msgtype", msgType);
        msgObj.put(msgType, obj);

        //设置参数
        postClient.addParameter("organizationCodes", "");
        postClient.addParameter("receiverIds", dingMsg.getReceiverUserids());
        postClient.addParameter("tenantId", "196729");
        postClient.addParameter("bizMsgId", "");
        postClient.addParameter("msg", msgObj.toJSONString());
        //调用API
        String apiResult = postClient.post();
        executableClient.destroy();
        JSONObject jsonObject = JSONObject.parseObject(apiResult);
        System.out.println(apiResult);
        if (jsonObject != null && jsonObject.getBoolean("success") == true) {
            return true;
        }
        return false;
    }


    public static ExecutableClient getExecutableClient() {
        ExecutableClient executableClient = ExecutableClient.getInstance();
        executableClient.setAccessKey("hlwjg_zszf-U0PRscL0Oh0XXyIRbE3");
        executableClient.setSecretKey("0eR4FJGY5T39E7ww533A6NOPg998o34ur05NP4Up");
        executableClient.setDomainName("openplatform-pro.ding.zj.gov.cn");
        executableClient.setProtocal("https");
        executableClient.init();
        return executableClient;
    }

    /**
     * 创建请求发送
     *
     * @param dingId   发送的钉id
     * @param title    发送标题
     * @param msg      发送正文
     * @param btnTitle
     * @param url      跳转地址
     * @return
     */
    public static DingMsg createDing(String dingId, String title, String msg, String btnTitle, String url) {
        DingMsg dingMsg = new DingMsg();
        dingMsg.setSendUserid("");
        dingMsg.setReceiverUserids(dingId);
        DingDingDto dto = new DingDingDto();
        dto.setTitle(title);
        dto.setDingMsg(msg);
        dto.setDingMsgType("action_card");

        List<BtnJsonList> btnJsonListList = new ArrayList<>();
        BtnJsonList btn = new BtnJsonList();
        btn.setTitle(btnTitle);
        btn.setActionUrl(url);
        btnJsonListList.add(btn);
        dto.setBtnJsonListList(btnJsonListList);
        dingMsg.setDingDingDto(dto);
        return dingMsg;
    }

    public static String getAccountIdByMobile(String mobile) {
        ExecutableClient executableClient = getExecutableClient();
        PostClient postClient = executableClient.newPostClient("/mozi/employee/get_by_mobile");
        //设置参数
        postClient.addParameter("areaCode", "86");
        postClient.addParameter("tenantId", "196729");
        postClient.addParameter("namespace", "local");
        postClient.addParameter("mobile", mobile);
        //调用API
        String apiResult = postClient.post();
        System.out.println(apiResult);

        if (StringUtils.isBlank(apiResult)) {
            executableClient.destroy();
            return null;
        }
        JSONObject resultObj = JSONObject.parseObject(apiResult);
        Object content = resultObj.get("content");
        JSONObject contentObj = JSONObject.parseObject(content.toString());
        boolean success = (boolean) contentObj.get("success");
        executableClient.destroy();
        if (success) {
            JSONObject data = JSONObject.parseObject(contentObj.get("data").toString());
            return data.get("accountId").toString();
        }
        return null;
    }


    /**
     * 模板1-
     * 审批-审批人----新的审批任务提示
     *
     * @param orgName      办案机构名称
     * @param documentName 文书名称
     * @param dingId       审批人dingId
     * @param timeLimit    时效
     * @param url          链接
     * @return boolean
     */
    public static boolean newAuditMsg(String orgName, String documentName, String dingId, String timeLimit, String url) {
        String title = "新的审批任务提示";
        String msg = "您有一份来自于" + orgName + "的【" + documentName + "】待审批，审批时效" + timeLimit + "，请前往审批任务列表查看";
        DingMsg dingMsg = createDing( dingId, title, msg, "去审核", url);
        return sendWorkNotification(dingMsg);
    }

    /**
     * 模板2-
     * 审批-审批人----审批通过
     *
     * @param url          链接
     * @param documentName 文书名称
     * @param dingId       审批人dingId
     * @param sendId       审批人id
     * @return boolean
     */
    public static boolean auditPassMsg(String documentName, String dingId, String sendId, String url) {
        String title = "审批通过提示";
        String msg = "您的【" + documentName + "】审批完成，点击查看审批详情。";

        DingMsg dingMsg = createDing( dingId, title, msg, "去查看", url);
        return sendWorkNotification(dingMsg);
    }

    /**
     * 模板3-
     * 审批-发起人----被审批通过
     *
     * @param url          链接
     * @param documentName 文书名称
     * @param dingId       审批人dingId
     * @return boolean
     */
    public static boolean auditedMsg(String documentName, String dingId, String url) {
        String title = "审批通过提示";
        String msg = "您的【" + documentName + "】审批完成，点击查看审批详情。";

        DingMsg dingMsg = createDing(dingId, title, msg, "去查看", url);
        return sendWorkNotification(dingMsg);
    }

    /**
     * 模板4-
     * 审批-发起人----被审批退回
     *
     * @param url          链接
     * @param documentName 文书名称
     * @param dingId       审批人dingId
     * @return boolean
     */
    public static boolean auditRetiredMsg(String documentName, String dingId,  String url) {
        String title = "审批通过提示";
        String msg = "您的【" + documentName + "】审批退回，点击查看审批详情。";

        DingMsg dingMsg = createDing( dingId, title, msg, "去查看", url);
        return sendWorkNotification(dingMsg);
    }

    /**
     * 模板5-
     * 办案人----案件到期提示
     *
     * @param url        链接
     * @param caseNumber 案件编号
     * @param dingId     审批人dingId
     * @param partyName   当事人
     * @param caseReason  案由
     * @return boolean
     */
    public static boolean expireMsg(String caseNumber, String expireTime, String dingId, String partyName, String caseReason, String url) {
        String title = "案件到期提示";
        String msg = "您编号【" + caseNumber + "】的案件将在" + expireTime + "后过期，请尽快处理\n\n"
                +"当事人："+partyName+"\n\n"
                +"案由："+caseReason;

        DingMsg dingMsg = createDing( dingId, title, msg, "去查看", url);
        return sendWorkNotification(dingMsg);
    }
    /**
     * 模板6-
     * 办案人----案件自动执行完毕
     *
     * @param url        链接
     * @param caseNumber 案件编号
     * @param dingId     审批人dingId
     * @param punishType   处罚种类
     * @param money       交款金额
     * @return boolean
     */
    public static boolean autoAuditMsg(String caseNumber, String punishType, String dingId, String money, String url) {
        String title = "案件自动执行完毕";
        String msg = "您编号【" + caseNumber + "】的案件自动执行完成。\n\n"
                +"处罚种类："+punishType
                +"\n\n缴费金额：人民币 "+money +"元整";
        DingMsg dingMsg = createDing( dingId, title, msg, "去查看", url);
        return sendWorkNotification(dingMsg);
    }

    /**
     * 模板7-
     * 办案人----文书送达临期提示
     *
     * @param url        链接
     * @param caseNumber 案件编号
     * @param dingId     审批人dingId
     * @param partyName   当事人
     * @param wsType       文书类型
     * @return boolean
     */
    public static boolean wsMomentMsg(String caseNumber, String partyName, String dingId, String wsType, String url) {
        String title = "文书送达临期提示";
        String msg = "您编号【" + caseNumber + "】的文书即将送达超期。"
                +"\n\n当事人："+partyName
                +"\n\n文书类型："+wsType ;
        DingMsg dingMsg = createDing( dingId, title, msg, "去处理", url);
        return sendWorkNotification(dingMsg);
    }

    /**
     * 模板8-
     * 办案人----案件缴费完成提示
     * @param url        链接
     * @param caseNumber 案件编号
     * @param dingId     审批人dingId
     * @param payType     缴费种类
     * @param money       缴费金额
     * @return boolean
     */
    public static boolean payFinishMsg(String caseNumber, String payType, String dingId, String money, String url) {
        String title = "案件缴费完成提示";
        String msg = "您编号【" + caseNumber + "】的案件缴费已完成。"
                +"\n\n缴费种类："+payType
                +"\n\n缴费金额：人民币"+money+"元" ;
        DingMsg dingMsg = createDing( dingId, title, msg, "去查看", url);
        return sendWorkNotification(dingMsg);
    }

    public static void main(String[] args) throws Exception {

       //  String dingId =  DingSendUtil.getAccountIdByMobile("18758550527");//徐立峰 18668800663  李亚锋18868876270
        //77619763
        //const urlQuery = encodeURIComponent('{"id":"b0f63cabe15047a4a35be1b1ce597411","documentCatalogCode":"LASPBAF49E","taskStatus":0,"waitStatus":2}')
        //`http://192.168.3.8:8080/transition-page?accountId=77619763&path=/my-approve/audit-detail&query=${urlQuery}`
       /* String a = "{\"id\":\"b0f63cabe15047a4a35be1b1ce597411\",\"documentCatalogCode\":\"LASPBAF49E\",\"taskStatus\":0,\"waitStatus\":2}" ;
        String url = "http://192.168.1.155:8002/zsba-h5/transition-page?accountId=77619763&path=/my-approve/audit-detail&query="+ URLEncoder.encode(a);
        boolean f5 = DingSendUtil.expireMsg("台综执第570号", "2小时", "77619763","徐立峰123","乱丢垃圾", url);
*/
        //"receiverAddress":{"lat":30.27751,"lng":120.14989,"address":"杭州市拱墅区蓝天商务中心"}
        String str =",'address':'杭州市拱墅区蓝天商务中心'}";

        System.out.println("----------------" + str.substring(str.indexOf("address")+10,str.length()-2));
    }

}
